package net.lab1024.sa.base.module.support.job.sample;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.domain.EventBaseAlert;
import net.lab1024.sa.base.config.CacheData;
import net.lab1024.sa.base.kafka.KafkaProducerService;
import net.lab1024.sa.base.module.support.elasticsearch.domain.form.EventBaseEsQueryForm;
import net.lab1024.sa.base.module.support.elasticsearch.service.EventBaseEsService;
import net.lab1024.sa.base.module.support.job.core.SmartJob;
import net.lab1024.sa.base.module.support.wxsm.dao.WxsmDao;
import net.lab1024.sa.base.module.support.wxsm.domain.entity.WxsmEntity;
import net.lab1024.sa.base.utils.KvMarkdownMessage;
import net.lab1024.sa.base.utils.MvelUtils;
import net.lab1024.sa.base.utils.ReflectionUtil;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务 示例2
 *
 * @author huke
 * @Date 2025/6/17 21:30
 */
@Slf4j
@Service
public class WxSmsSend implements SmartJob {

    @Autowired
    private RestHighLevelClient esClient;
    @Resource
    private WxsmDao wxsmDao;
    @Autowired
    private CacheData cacheService;
    @Autowired
    private KafkaProducerService kafkaProducerService;
    @Autowired
    private EventBaseEsService eventBaseEsService;
    /**
     * 定时任务示例
     * 需要事务时 添加 @Transactional 注解
     *
     * @param param 可选参数 任务不需要时不用管
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public String run(String param) throws InvocationTargetException, IllegalAccessException {
        JSONObject jsonObject1 = JSONObject.parseObject(param);
        int listSize = 0;
        List<WxsmEntity> wxsmEntities = wxsmDao.selectList(new LambdaQueryWrapper<WxsmEntity>().eq(WxsmEntity::getSocStatus, 0));

        // 使用System.currentTimeMillis()获取当前时间戳
        long currentTime = System.currentTimeMillis();
        String key = "event-alert-time";

        // 从缓存获取上次执行时间
        Long lastExecuteTime = (Long) cacheService.get(key);
        long fiveMinutesAgo;

        if (lastExecuteTime != null) {
            fiveMinutesAgo = lastExecuteTime;
        } else {
            // 如果没有上次执行时间，则取5分钟前
            fiveMinutesAgo = currentTime - (jsonObject1.getInteger("nums") * 60 * 1000);
        }

        // 更新缓存中的时间戳
        cacheService.put(key, currentTime);

        // 构建查询请求
        EventBaseEsQueryForm request = new EventBaseEsQueryForm();
        request.setStartTime(fiveMinutesAgo);
        request.setEndTime(currentTime);
        log.info("开始执行定时任务 检索时间范围是,开始时间{},结束时间{}", fiveMinutesAgo, currentTime);
        request.setIndexName(jsonObject1.getString("indexName"));
//            request.setAisql(wxsmEntity.getEpl());

        request.setIndexName(jsonObject1.getString("indexName"));
        List<EventBaseAlert> eventBases = eventBaseEsService.queryListAlert(request);


        if (null == eventBases || eventBases.size()<=0) {
            return "未查询到数据";
        }

        Map<String, List<EventBaseAlert>> groupedByType = eventBases.stream().filter(s -> s.getSrcIp() != null)
                .collect(Collectors.groupingBy(EventBaseAlert::getSrcIp));
        listSize = groupedByType.size();
        for (Map.Entry<String, List<EventBaseAlert>> entry : groupedByType.entrySet()) {
            for (WxsmEntity wxsmEntity : wxsmEntities) {
                List<EventBaseAlert> value = entry.getValue();
                EventBaseAlert eventBaseAlert = value.get(0);
                eventBaseAlert.setGroupCount(value.size()+"");
                sendWxMessage(eventBaseAlert, wxsmEntity);

            }
        }
        return "执行成功,本次处理数据" + listSize + "条";
    }


    public void sendWxMessage(EventBaseAlert eventBase, WxsmEntity wx)
            throws InvocationTargetException, IllegalAccessException {

        String wxsign = wx.getWxsign();
//        wxsign = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9e03ab9c-be12-4cf8-b395-00672690b2b7";
        String epl = wx.getEpl();

        // 验证警报
        boolean validate = MvelUtils.validateAlert(eventBase, epl);
        if (validate) {
            String[] split = wxsign.split(";");
            kafkaProducerService.sendMessage("alert-wx-log", JSONObject.toJSONString(eventBase));
            log.info("kafka消息推送成功{}",eventBase.getEsId());
            if (null != split) {
                for (int i = 0; i < split.length; i++) {
                    // 解析微信消息模板
                    JSONObject json = JSONObject.parseObject(wx.getSmsTemp());
                    // 创建Markdown消息
                    KvMarkdownMessage message = new KvMarkdownMessage(split[i]);
                    message.setTitle(wx.getTitle());

                    // 遍历模板中的所有字段
                    for (String key : json.keySet()) {
                        String templateValue = json.getString(key);
                        // 从事件对象中获取字段值
                        String fieldValue = ReflectionUtil.getFieldValue(eventBase, templateValue);
                        message.addField(key, fieldValue==null?"":fieldValue);
                    }

                    log.info(message.toString());
                    try {
                        // 发送消息
                        message.send();
                        log.error("发送成功: " + message.toString());
                    } catch (Exception e) {
                        log.error("发送微信消息失败: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
